package com.viish.apps.tripletriad.carte;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TabHost.OnTabChangeListener;

import com.viish.apps.tripletriad.R;
import com.viish.apps.tripletriad.views.MinimalistCardView;

public class Shop extends TabActivity
// TODO : afficher gils + better UI
{
	public static final String CHEAT_ALLCARDS = "Catch'em all";
	public static final String CHEAT_DISSIDIA = "Special Reward";
	public static final String CHEAT_GILS = "Paycheck";
	public static final int SELL_PRICE_RATIO_LEVEL = 10;
	public static final int BUY_PRICE_RATIO_LEVEL = 100;
	public static final int BUY_TAB = 0;
	public static final int SELL_TAB = 1;
	public static final int CARD_SIZE = 87;
	
	private TabHost th;
	private LinearLayout options;
	private GridView buy, sell;
	private ArrayList<Card> cards, myCards;
	private CheckBox ff7, ff8, ff10, level6andLess, level7, level8, level9, level10;
	
	private OnCheckedChangeListener checkListener = new OnCheckedChangeListener()
	{
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean arg1) 
		{
			refreshCards();
		}
	};
	
	private OnTabChangeListener tabListener = new OnTabChangeListener() 
	{
		@Override
		public void onTabChanged(String tabId) 
		{
//			refreshCards(th.getCurrentTab() == SELL_TAB);
		}
	};
	
	private OnClickListener clicListener = new OnClickListener()
	{
		@Override
		public void onClick(View v) 
		{
			final MinimalistCardView cardView = (MinimalistCardView) v;
			
			if (cardView.getCardEdition() == 0)
				return;
			
			String title = th.getCurrentTab() == SELL_TAB ? getString(R.string.confirmation_sell_title) : getString(R.string.confirmation_buy_title);
			String message = th.getCurrentTab() == SELL_TAB ? getString(R.string.confirmation_sell_message) : getString(R.string.confirmation_buy_message);
			int price = th.getCurrentTab() == SELL_TAB ? cardView.getCardLevel() * SELL_PRICE_RATIO_LEVEL : cardView.getCardLevel() * BUY_PRICE_RATIO_LEVEL;
			message += " " + cardView.getCardName() + " " + getString(R.string.confirmation_junction) + " " + price + " Gils ?";

			LinearLayout ll = new LinearLayout(v.getContext());
			ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			ll.setOrientation(LinearLayout.HORIZONTAL);
			ll.setGravity(Gravity.CENTER);
			ll.addView(cardView.clone(false));
			TextView confirmation = new TextView(v.getContext());
			confirmation.setText(message);
			confirmation.setGravity(Gravity.CENTER);
			ll.addView(confirmation);

			Builder alert = new AlertDialog.Builder(v.getContext());
			alert.setTitle(title);
			alert.setView(ll);		
			alert.setNeutralButton(R.string.button_back, null);
			if (th.getCurrentTab() == BUY_TAB)
			{
				alert.setPositiveButton(R.string.button_buy, new DialogInterface.OnClickListener() 
				{
					@Override
					public void onClick(DialogInterface dialog, int which) 
					{
						DatabaseStream dbs = new DatabaseStream(cardView.getContext());
						int cardPrice = cardView.getCardLevel() * BUY_PRICE_RATIO_LEVEL;
						int myGils = dbs.getGils();
						if (myGils > cardPrice)
						{
							dbs.setGils(myGils - cardPrice);
							dbs.nouvelleCarte("ff" + cardView.getCardEdition() + "/" + cardView.getCardName());
					        myCards = sortByLevel(dbs.getMyCards());
							refreshMyCards();
						}
						else
						{
							Toast.makeText(cardView.getContext(), getString(R.string.notenoughgils), Toast.LENGTH_LONG).show();
						}
						dbs.close();
					}
				});
			}
			else if (th.getCurrentTab() == SELL_TAB)
			{
				alert.setPositiveButton(R.string.button_sell, new DialogInterface.OnClickListener() 
				{
					@Override
					public void onClick(DialogInterface dialog, int which) 
					{
						if (myCards.size() > 5)
						{
							DatabaseStream dbs = new DatabaseStream(cardView.getContext());
							
							int cardPrice = cardView.getCardLevel() * SELL_PRICE_RATIO_LEVEL;
							int myGils = dbs.getGils();
							dbs.setGils(myGils + cardPrice);
							
							dbs.supprimerCarte("ff" + cardView.getCardEdition() + "/" + cardView.getCardName());
							myCards = sortByLevel(dbs.getMyCards());
							refreshMyCards();
							dbs.close();
						}
						else
						{
							Toast.makeText(cardView.getContext(), R.string.mincardreached, Toast.LENGTH_LONG).show();
						}
					}
				});
			}
			alert.show();
		}
	};
	
	private void showCheatPopup()
	{
		Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Cheat Mode !");
		alert.setIcon(R.drawable.pampa);
		
		final EditText cheatcode = new EditText(this);
		cheatcode.setText(CHEAT_GILS);
		alert.setView(cheatcode);
		
		alert.setNegativeButton(R.string.button_back, null);
		alert.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() 
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				if (cheatcode.getText().toString().equals(CHEAT_GILS))
				{
					Log.d("Cheat", cheatcode.getText().toString());
					final ProgressDialog mProgress = new ProgressDialog(cheatcode.getContext());
					mProgress.setTitle("Please wait ...");
					mProgress.setOnDismissListener(new OnDismissListener() 
					{
						@Override
						public void onDismiss(DialogInterface dialog) 
						{
							try
							{
								Toast.makeText(cheatcode.getContext(), R.string.cheat_dissidia, Toast.LENGTH_SHORT).show();
//								Toast.makeText(cheatcode.getContext(), R.string.cheat_allcards, Toast.LENGTH_SHORT).show();
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
					});
					new Thread(new Runnable() 
					{
			             @Override
						public void run() 
			             {
			                try 
							{
			                	DatabaseStream dbs = new DatabaseStream(cheatcode.getContext());
//								dbs.unlockAllCards();
//								dbs.unlockDissidiaCards();
			                	dbs.setGils(1000000000);
						        myCards = dbs.getMyCards();
						        cards = dbs.getAllCards();
								dbs.close();
						        myCards = sortByLevel(myCards);
								
								refreshCards();
							} 
							catch (Exception e) 
							{
								e.printStackTrace();
							}
							finally
							{
								mProgress.dismiss();
							}
			             }
			         }).start();
					mProgress.show();
				}
			}
		});
		alert.show();
	}
	
	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) 
	{
		if (keyCode == KeyEvent.KEYCODE_SEARCH)
		{
			showCheatPopup();
			return true;
		}
		return false;
	};
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) 
	{
		if (options.getVisibility() == View.GONE)
		{
			options.setVisibility(View.VISIBLE);
			th.getTabWidget().setVisibility(View.VISIBLE);
		}
		else 
		{
			options.setVisibility(View.GONE);
			th.getTabWidget().setVisibility(View.GONE);
		}
		
		return false;
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.shop);

		DatabaseStream dbs = new DatabaseStream(this);
        myCards = sortByLevel(dbs.getMyCards());
        cards = dbs.getAllCards();
        dbs.close();

        int columns = getWindowManager().getDefaultDisplay().getWidth() / CARD_SIZE;
        buy = (GridView) findViewById(R.id.buy);
        buy.setNumColumns(columns);
        sell = (GridView) findViewById(R.id.sell);
        sell.setNumColumns(columns);
        options = (LinearLayout) findViewById(R.id.optionsLL);
        
        ff7 = (CheckBox) findViewById(R.id.cbFFVII);
        ff7.setOnCheckedChangeListener(checkListener);
        ff8 = (CheckBox) findViewById(R.id.cbFFVIII);
        ff8.setOnCheckedChangeListener(checkListener);
        ff10 = (CheckBox) findViewById(R.id.cbFFX);
        ff10.setOnCheckedChangeListener(checkListener);

        level6andLess = (CheckBox) findViewById(R.id.cblevel6);
        level6andLess.setOnCheckedChangeListener(checkListener);
        level7 = (CheckBox) findViewById(R.id.cblevel7);
        level7.setOnCheckedChangeListener(checkListener);
        level8 = (CheckBox) findViewById(R.id.cblevel8);
        level8.setOnCheckedChangeListener(checkListener);
        level9 = (CheckBox) findViewById(R.id.cblevel9);
        level9.setOnCheckedChangeListener(checkListener);
        level10 = (CheckBox) findViewById(R.id.cblevel10);
        level10.setOnCheckedChangeListener(checkListener);
        
        th = getTabHost();
        th.setOnTabChangedListener(tabListener);
	    th.addTab(th.newTabSpec("Buy").setIndicator("Buy").setContent(R.id.buy));
	    th.addTab(th.newTabSpec("Sell").setIndicator("Sell").setContent(R.id.sell));
	    th.setCurrentTab(BUY_TAB);
        
	    sell.setAdapter(new CardAdapter(this, myCards, true));
        buy.setAdapter(new CardAdapter(this, cards, false));
        
        Toast.makeText(this, getString(R.string.howtodisplaymenu), Toast.LENGTH_LONG).show();
    }
	
	private void refreshCards()
	{        
		ArrayList<Card> allFilteredCards = new ArrayList<Card>();
		
		for (Card card : cards)
		{
			int level = card.getLevel();
			int episode = card.getEdition();
			if (((level <= 6 && level6andLess.isChecked()) || (level == 7 && level7.isChecked()) || (level == 8 && level8.isChecked()) || (level == 9 && level9.isChecked()) || (level == 10 && level10.isChecked())) 
					&& ((ff7.isChecked() && episode == 7) || (ff8.isChecked() && episode == 8) || (ff10.isChecked() && episode == 10) || episode == 0))
				allFilteredCards.add(card);
		}
        buy.setAdapter(new CardAdapter(this, allFilteredCards, false));
        
        refreshMyCards();
	}
	
	private void refreshMyCards()
	{
		ArrayList<Card> myFilteredCards = new ArrayList<Card>();
		for (Card card : myCards)
		{
			int level = card.getLevel();
			int episode = card.getEdition();
			if (((level <= 6 && level6andLess.isChecked()) || (level == 7 && level7.isChecked()) || (level == 8 && level8.isChecked()) || (level == 9 && level9.isChecked()) || (level == 10 && level10.isChecked())) 
					&& ((ff7.isChecked() && episode == 7) || (ff8.isChecked() && episode == 8) || (ff10.isChecked() && episode == 10) || episode == 0))
				myFilteredCards.add(card);
		}
		sell.setAdapter(new CardAdapter(this, myFilteredCards, true));
	}
	
	private ArrayList<Card> sortByLevel(ArrayList<Card> cards)
	{
		ArrayList<Card> sortedCards = new ArrayList<Card>();
		for (int i = 0; i <= 10; i++)
		{
			for (Card c : cards)
			{
				if (c.getLevel() == i)
				{
					sortedCards.add(c);
				}
			}
		}
		return sortedCards;
	}
	
	class CardAdapter extends BaseAdapter
	{	
	    private Context mContext;
	    private ArrayList<Card> mThumbIds;
	    private boolean useSellRatio;

	    public CardAdapter(Shop shop, ArrayList<Card> cards, boolean useSellRatio) 
	    {
	        mContext = shop;
	        mThumbIds = cards;
	        this.useSellRatio = useSellRatio;
	    }

		@Override
		public int getCount() 
	    {
	        return mThumbIds.size();
	    }

		@Override
		public Object getItem(int position) 
	    {
	        return mThumbIds.get(position);
	    }

		@Override
		public long getItemId(int position) 
	    {
	        return 0;
	    }

		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
	    {
	        View v;
	        TextView tv;
	        MinimalistCardView cv;
	        
	        if(convertView == null)
	        {
	                LayoutInflater li = ((Activity) mContext).getLayoutInflater();
	                v = li.inflate(R.layout.icon, null); 
	        }
	        else
	        {
	                v = convertView;
	        }
	        
	        v.setPadding(5, 5, 5, 5);
	        
	        cv = (MinimalistCardView) v.findViewById(R.id.icon_image);
	        cv.setAdjustViewBounds(true);
	        cv.setOnClickListener(clicListener);
	        
	        tv = (TextView) v.findViewById(R.id.icon_text);
	        Card card = mThumbIds.get(position);
	        try 
		 	{
	        	int level = card.getLevel();	        	
	        	int price = level;
	        	if (card.getEdition() != 0)
	        	{
		        	if (useSellRatio) 
		        		price *= Shop.SELL_PRICE_RATIO_LEVEL;
		        	else 
		        		price *= Shop.BUY_PRICE_RATIO_LEVEL;
		            tv.setText(price + "");
		            
		            DatabaseStream dbs = new DatabaseStream(mContext);
		            if (dbs.getGils() >= price)
		            	tv.setTextColor(Color.YELLOW);
		            else
			            tv.setTextColor(Color.RED);
		            dbs.close();
	        	}
	        	else
	        	{
	        		tv.setText(getString(R.string.unavailable));
		            tv.setTextColor(Color.RED);
	        	}
	            
	        	Bitmap bm = BitmapFactory.decodeStream(mContext.getResources().getAssets().open(card.getFullName() + ".1.png"));
	        	cv.setImage(bm);
	        	cv.setCard(card);
	        	cv.invalidate();
		 	} 
		 	catch (Exception e) 
		 	{
				e.printStackTrace();
		 	}
	        
	        return v;
	    }
	}
}